<template>
    <header class="sticky top-0 z-20 dark:bg-stone-950">
        <nav class="bg-white border-gray-200 border-b dark:bg-stone-950">
            <div class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-4">
                <!-- 博客 LOGO 、博客名称 -->
                <a href="/" class="flex items-center">
                    <el-image class="h-8 mr-3 rounded-full" :src="blogSettingsStore.blogSettings.logo" alt=""
                        @click="goArticleDetailPage(article.id)">
                        <template #error>
                            <div class="flex items-center w-full h-full justify-center">
                                <el-icon :size="20"><icon-picture /></el-icon>
                            </div>
                        </template>
                    </el-image>
                    <!-- <img :src="blogSettingsStore.blogSettings.logo" class="h-8 mr-3 rounded-full" alt="Logo" /> -->
                    <span class="hidden md:flex self-center text-2xl font-semibold whitespace-nowrap dark:text-white">
                        {{ blogSettingsStore.blogSettings.name }}</span>
                </a>

                <div class="flex items-center md:order-2">
                    <!-- 搜索框 -->
                    <button type="button" @click="clickSearchBtn" class="hidden md:flex mr-2 outline-none items-center text-sm leading-6 text-slate-400 
                        rounded-md ring-1 ring-slate-900/10 shadow-sm py-1.5 pl-2 pr-3 hover:ring-slate-300 
                        dark:bg-slate-800 dark:highlight-white/5 dark:hover:bg-slate-700">
                        <svg-icon name="search-article" class="w-3.5 h-3.5 mr-2 text-gray-500 dark:text-gray-400"
                            aria-hidden="true" />
                        <span class="mr-3">搜索文章 ...</span>
                        <span class="px-2 py-[1px] flex-none text-xs border text-gray-400 rounded">Ctrl K</span>
                    </button>
                    <!-- 手机端搜索按钮 -->
                    <button type="button" @click="clickSearchBtn" class="md:hidden sm:flex  outline-none items-center ">
                        <svg-icon name="search-article" class="w-6 h-6 mr-2 text-gray-500 dark:text-gray-400"
                            aria-hidden="true" />
                    </button>

                    <div>
                        <Dark></Dark>
                    </div>
                    <!-- 登录 -->
                    <div v-if="!isLogined" class="text-gray-900 ml-2 mr-2 hover:text-blue-700 dark:text-white"
                        @click="$router.push('/login')">登录</div>
                    <!-- 已经登录，展示用户头像 -->
                    <button v-else id="dropdownDefaultButton" data-dropdown-toggle="dropdown" class="text-white ml-2 mr-2 md:mr-0 focus:ring-4 focus:ring-blue-300 font-medium 
                        rounded-full text-sm text-center inline-flex items-center dark:bg-blue-600 
                        dark:hover:bg-blue-700 dark:focus:ring-blue-800" type="button">
                        <!-- 用户登录头像 -->
                        <span class="el-dropdown-link flex items-center justify-center text-gray-700 text-xs">
                            <el-avatar :size="30" :src="blogSettingsStore.blogSettings.avatar" @error="errorHandler">
                                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                            </el-avatar>
                        </span>
                    </button>

                    <!-- Dropdown menu -->
                    <div id="dropdown"
                        class="z-10 hidden bg-white divide-y divide-gray-100 rounded-lg shadow dark:bg-gray-700">
                        <ul class="py-2 text-sm text-gray-700 dark:text-gray-200"
                            aria-labelledby="dropdownDefaultButton">
                            <li>
                                <a @click="router.push('/admin/index')"
                                    class="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">
                                    <Platform class="inline w-3 h-3 mb-[2px] mr-1 text-gray-700 dark:text-white" />
                                    进入后台
                                </a>
                            </li>
                            <li>
                                <a @click="logoutModal.show()"
                                    class="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">
                                    <svg-icon name="logout"
                                        class="inline w-3 h-3 mb-[2px] mr-1 text-gray-700 dark:text-white"
                                        aria-hidden="true" />
                                    退出登录
                                </a>
                            </li>
                        </ul>
                    </div>


                    <!-- 手机端菜单 -->
                    <!-- <button data-collapse-toggle="navbar-search" type="button" class="inline-flex items-center p-2 w-10 h-10 justify-center text-sm text-gray-500 rounded-lg 
                        md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 
                        dark:hover:bg-gray-700 dark:focus:ring-gray-600" aria-controls="navbar-search"
                        aria-expanded="false"> -->
                    <!-- <svg-icon name="menu" class="w-5 h-5" aria-hidden="true" /> -->
                    <!-- </button> -->
                    <button data-collapse-toggle="navbar-search" aria-controls="navbar-search"
                        class="inline-flex md:hidden">
                        <IconCatalogue></IconCatalogue>
                    </button>
                </div>
                <div class="items-center justify-between hidden w-full md:flex md:w-auto md:order-1" id="navbar-search">
                    <ul
                        class="flex flex-col p-4 md:p-0 mt-4 font-medium border border-gray-100 rounded-lg bg-gray-50 md:flex-row md:space-x-8 md:mt-0 md:border-0 md:bg-white dark:bg-stone-950 md:dark:bg-stone-950 dark:border-gray-700">
                        <li>
                            <a @click="router.push('/')"
                                :class="[currPath == '/' ? 'text-blue-700' : 'text-gray-900 dark:text-white']"
                                class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:p-0 md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700"
                                aria-current="page">首页</a>
                        </li>
                        <li>
                            <a @click="router.push('/category/list')"
                                :class="[currPath == '/category/list' || currPath == '/category/article/list' ? 'text-blue-700' : 'text-gray-900 dark:text-white']"
                                class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:p-0 md:dark:hover:text-blue-500  dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">分类</a>
                        </li>
                        <li>
                            <a @click="router.push('/tag/list')"
                                :class="[currPath == '/tag/list' || currPath == '/tag/article/list' ? 'text-blue-700' : 'text-gray-900 dark:text-white']"
                                class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:p-0  md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">标签</a>
                        </li>
                        <li>
                            <a @click="router.push('/wiki/list')"
                                :class="[currPath.startsWith('/wiki') ? 'text-blue-700' : 'text-gray-900 dark:text-white']"
                                class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:p-0  md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">知识库</a>
                        </li>
                        <li>
                            <a @click="router.push('/archive/list')"
                                :class="[currPath == '/archive/list' ? 'text-blue-700' : 'text-gray-900 dark:text-white']"
                                class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:p-0  md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">归档</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <!-- 退出登录 -->
    <div id="logout-modalEl" tabindex="-1"
        class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
        <div class="relative p-4 w-full max-w-2xl max-h-full">
            <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
                <button type="button"
                    class="absolute top-3 right-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ml-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white"
                    @click="logoutModal.hide()">
                    <svg-icon name="X" class="w-3 h-3" aria-hidden="true" />
                    <span class="sr-only">Close modal</span>
                </button>
                <div class="p-6 text-center">
                    <svg-icon name="warning" class="mx-auto mb-4 text-gray-400 w-12 h-12 dark:text-gray-200"
                        aria-hidden="true" />
                    <h3 class="mb-5 text-lg font-normal text-gray-500 dark:text-gray-400">确定退出登录?
                    </h3>
                    <button @click="logout" type="button"
                        class="text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2">
                        确定
                    </button>
                    <button @click="logoutModal.hide()" type="button"
                        class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600">
                        取消</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 站内搜索 -->
    <div id="search-modalEl" tabindex="-1" aria-hidden="true"
        class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
        <div class="relative p-4 w-full max-w-2xl max-h-full">
            <!-- Modal content -->
            <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
                <!-- Modal header -->
                <div class="flex items-center justify-between p-4 md:p-5 border-b rounded-t dark:border-gray-600">
                    <!-- 搜索框 -->
                    <form class="w-full mr-2">
                        <label for="search"
                            class="mb-2 text-sm font-medium text-gray-900 sr-only dark:text-white">Search</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 start-0 flex items-center ps-3 pointer-events-none">
                                <div v-if="searchLoading" role="status">
                                    <svg-icon name="loading" aria-hidden="true"
                                        class="w-4 h-4 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600"></svg-icon>
                                    <span class="sr-only">Loading...</span>
                                </div>
                                <svg-icon v-else name="search-article" class="w-4 h-4 text-gray-500 dark:text-gray-400"
                                    aria-hidden="true" />

                            </div>
                            <input type="search" id="search" ref="searchInputRef" v-model="searchWord"
                                class="block w-full p-4 ps-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                                placeholder="请输入关键词搜索..." required>
                        </div>
                    </form>
                    <button type="button" @click="searchModal.hide()"
                        class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white">
                        <svg-icon name="X" class="w-3 h-3"></svg-icon>
                        <span class="sr-only">Close modal</span>
                    </button>
                </div>
                <!-- Modal body -->
                <div class="p-4 md:p-5 space-y-4">
                    <div v-if="searchArticles && searchArticles.length > 0">
                        <p class="text-base leading-relaxed text-gray-500 dark:text-gray-400">
                            共搜索到 {{ total }} 篇相关文章
                        </p>
                        <ol class="mt-3 divide-y divider-gray-200 dark:divide-gray-700">
                            <li v-for="(article, index) in searchArticles" :key="index">
                                <a @click="jumpToArticleDetailPage(article.id)"
                                    class="items-center cursor-pointer block p-3 sm:flex hover:bg-gray-100 hover:rounded-lg dark:hover:bg-gray-700">
                                    <img class="w-24 h-full mb-3 mr-3 rounded-lg sm:mb-0" :src="article.cover">
                                    <div class="text-gray-600 dark:text-gray-400">
                                        <h2 class="text-base font-normal text-gray-900" v-html="article.title"></h2>
                                        <div>
                                            <span class="mr-7"></span>
                                            <span class="text-base font-normal" v-html="article.summary"></span>
                                        </div>
                                        <span
                                            class="inline-flex items-center text-xs font-normal text-gray-500 dark:text-gray-400">
                                            <svg-icon name="search-calendar"
                                                class="inline w-3.5 h-3.5 mr-2 text-gray-400 dark:text-white"
                                                aria-hidden="true" />
                                            {{ article.createDate }}</span>
                                    </div>
                                </a>
                            </li>
                        </ol>
                        <!-- 分页 -->
                        <div class="flex mt-7">
                            <a v-if="current > 1" @click="prePage"
                                class="flex items-center justify-center px-3 h-8 me-3 text-xs font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-stone-950 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
                                <svg-icon name="pre-page-f" class="w-3 h-3 rtl:rotate-180" aria-hidden="true" />

                            </a>

                            <a v-if="current < pages" @click="nextPage"
                                class="flex ml-auto items-center justify-center px-3 h-8 text-xs font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-stone-950 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
                                <svg-icon name="next-page-f" class="w-3 h-3 rtl:rotate-180" aria-hidden="true" />

                            </a>
                        </div>
                    </div>
                    <div v-else class="flex items-center justify-center flex-col mb-10 md:mb-5">
                        <svg-icon name="search-null" size="100"></svg-icon>
                        <p class="text-gray-600 text-sm">未查询到结果, 换个姿势搜索吧~</p>
                    </div>

                </div>
                <!-- Modal footer -->
                <div class="p-4 md:p-5 border-t text-xs flex items-center text-gray-400">
                    <!-- Esc 退出提示 -->
                    <span class="md:flex hidden px-2 py-[1px] flex-none border rounded">Esc</span>
                    <span class="md:flex hidden text-gray-400 ml-2">关闭</span>

                    <!-- 底层技术介绍 -->
                    <span class="ml-auto">基于 <a href="https://lucene.apache.org/" target="_blank"
                            class="underline">Apache
                            Lucene</a> 全文检索引擎开发</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount, watch } from 'vue'
import { useBlogSettingsStore } from '@/stores/blogsettings'
import { useUserStore } from '@/stores/user'
import { useRouter, useRoute } from 'vue-router'
import { Modal } from 'flowbite'
import { getArticleSearchPageList } from '@/api/frontend/search'
import { showMessage } from '@/composables/util'
import Dark from '@/components/Dark.vue'
import IconCatalogue from '@/components/icons/IconCatalogue.vue'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { useIpStore } from '@/stores/ip'


const router = useRouter()
const route = useRoute()
const useIp = useIpStore()

// 搜索输入框引用
const searchInputRef = ref(null)
let searchModal = ref(null)
let logoutModal = ref(null)
// 初始化 flowbit 相关组件
onMounted(() => {
    console.log("初始化modal")
    initCollapses();
    initDropdowns();
    // initModals();
    // 初始化搜索模态
    const $modalElement = document.getElementById('search-modalEl');
    searchModal = new Modal($modalElement, modalOptions, instanceOptions);
    // 初始化退出登录模态
    const $logoutModaElement = document.getElementById('logout-modalEl');
    logoutModal = new Modal($logoutModaElement, modalOptions, logoutInstanceOptions);
    // 注册键盘事件监听器
    window.addEventListener('keydown', handleKeyDown);
    //访问则会记录ip,并记录到全局
    useIp.setIp();
})

onBeforeUnmount(() => {
    // 在组件销毁前移除事件监听器，防止内存泄漏
    window.removeEventListener('keydown', handleKeyDown);
})

// 键盘监听
const handleKeyDown = (event) => {
    // 检查是否按下了 Ctrl 键和 K 键
    if (event.ctrlKey && event.key === 'k') {
        // 阻止激活浏览器本身的搜索框
        event.preventDefault()
        console.log('ctrl k 被按了')

        searchModal.show()

        // 激活搜索框
        searchInputRef.value.focus()
    }
}

// 引入博客设置信息 store
const blogSettingsStore = useBlogSettingsStore()

// 是否登录，通过 userStore 中的 userInfo 对象是否有数据来判断
const userStore = useUserStore()
// 获取 userInfo 对象所有属性名称的数组
const keys = Object.keys(userStore.userInfo)
// 若大于零，则表示用户已登录
const isLogined = ref(keys.length > 0)

// 退出登录
const logout = () => {
    logoutModal.hide()
    userStore.logout()
    // 标记为未登录
    isLogined.value = false
    showMessage('退出登录成功')
}

// 当前路由地址
const currPath = ref(route.path)

const errorHandler = () => true


const modalOptions = {
    placement: 'top-center', // 弹框位置
    backdrop: 'dynamic',
    backdropClasses:
        'bg-gray-900/50 dark:bg-stone-950/80 fixed inset-0 z-40',
    closable: true,
    onHide: () => {
        console.log('modal is hidden');
    },
    onShow: () => {
        console.log('modal is shown');
    },
    onToggle: () => {
        console.log('modal has been toggled');
    },
};

// instance options object
const instanceOptions = {
    id: 'search-modalEl',
    override: true
};

const logoutInstanceOptions =
{
    id: 'logout-modalEl',
    override: true
}



// 点击搜索框
const clickSearchBtn = () => {
    searchModal.show()
    // 激活搜索框
    searchInputRef.value.focus()
}


// 文章搜索结果
const searchArticles = ref([])
// 当前页码，给了一个默认值 1
const current = ref(1)
// 总数据量，给了个默认值 0
const total = ref(0)
// 每页显示的数据量，给了个默认值 10
const size = ref(10)
// 总共多少页
const pages = ref(0)
// 搜索关键词
const searchWord = ref('')

// 侦听属性，监听 searchWord 变量变化
watch(searchWord, (newText, oldText) => {
    console.log(`新值: ${newText}, 老值: ${oldText}`)
    if (newText && newText !== oldText) { // 若搜索关键词不为空，且和之前的值不相同
        renderSearchArticles({ current: current.value, size: size.value, word: newText })
    } else if (newText == '') { // 搜索词为空
        // 置空
        searchArticles.value = []
    }
})


// 搜索 Loading
const searchLoading = ref(false)
// 请求后台检索接口
function renderSearchArticles(data) {
    // 显示加载 Loading
    searchLoading.value = true
    getArticleSearchPageList(data).then(res => {
        console.log(res)
        if (res.success) {
            searchArticles.value = res.data
            current.value = res.current
            size.value = res.size
            total.value = res.total
            pages.value = res.pages
        }
    }).finally(() => searchLoading.value = false) // 隐藏加载 Loading
}

// 渲染下一页搜索结果
const nextPage = () => {
    renderSearchArticles({ current: current.value + 1, size: size.value, word: searchWord.value })
}

// 渲染上一页搜索结果
const prePage = () => {
    renderSearchArticles({ current: current.value - 1, size: size.value, word: searchWord.value })
}


// 点击搜索结果，跳转文章详情页
const jumpToArticleDetailPage = (articleId) => {
    // 隐藏搜索对话框
    searchModal.hide()
    // 路由跳转
    router.push('/article/' + articleId)
}




</script>
